﻿using System;
using System.Linq;
using umbraco.cms.presentation.Trees;
using Umbraco.Core;
using Umbraco.Core.Services;
using config = objectOutlet.Umbraco.ConnectedPages.Config.ConnectedPagesConfig;

namespace objectOutlet.Umbraco.ConnectedPages.Startup
{
	public class RelationsTreeviewHandler : IApplicationEventHandler
	{
		public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
		{ }

		public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
		{
			BaseTree.BeforeNodeRender += BaseTree_BeforeNodeRender;
		}

		public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
		{ }

		public void BaseTree_BeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e)
		{
			if (!config.Current.ShowIconOverlays)
				return;
			if (node.NodeType != "content")
				return;

			var cs = new ContentService();
			var rs = ApplicationContext.Current.Services.RelationService;

			int nodeId;
			int.TryParse(node.NodeID, out nodeId);

			var relations = rs.GetByParentOrChildId(nodeId).Where(x => x.RelationType.Alias == config.Current.RelationTypeAlias);
			if (!relations.Any())
				return;

			node.IconClass = String.Concat(node.IconClass, " oo_connectedpage"); // <-------------- "oo_connectedpage" er CSS klassenavnet hvor vi smider vores icon overlay styling i
		}
	}
}